﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace Kis2012.Models
{
    public class UsersTable
    {
        private Table<User> usersTable;
        private DataContext context;

        public UsersTable() 
        {
            string connStr = ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;
            context = new DataContext(connStr);
            usersTable = context.GetTable<User>();
        }

        public User GetUserByName(string Name, string Pass)
        {
            User user = usersTable.SingleOrDefault(u => u.LoginName == Name && u.LoginPass == Pass);
            return user;
        }

        public User GetUserByName(string Name)
        {
            User user = usersTable.SingleOrDefault(u => u.LoginName == Name);
            return user;
        }

        public IEnumerable<User> GetAllUsers()
        {
            return usersTable.AsEnumerable();
        }

        public int RegisterUser(RegisterModel newUser)
        {
            User user = new User();
            user.LoginName = newUser.UserName;
            user.LoginPass = GetMD5Hash(newUser.Password);
            user.UserEmailAddress = newUser.Email;
            user.UserName = newUser.UserName;
            user.UserFullName = newUser.FullName;
            user.IsAdmin = 0;
            user.IsActive = 1;
            user.UserUnit = newUser.UnitName;
            user.UserDept = 0;
            usersTable.InsertOnSubmit(user);
            context.SubmitChanges();
            
            return user.UserId;
        }

        public bool UpdateUser(string userName, string oldPass, string newPass)
        {
            User user = usersTable.SingleOrDefault(u => u.LoginName == userName && u.LoginPass == GetMD5Hash(oldPass));
            if (user != null)
            {
                user.LoginPass = GetMD5Hash(newPass);
                context.SubmitChanges();
                return true;
            }
            return false;
        }

        private string GetMD5Hash(string password)
        {
            MD5 md5 = MD5.Create();
            byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(password));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
    }
}